#pragma once
#include "BlockQueue.hpp"
#include "Task.hpp"

template<typename T>
class ThreadPool
{
public:
    // 获取线程池实例（懒汉式单例）
    static ThreadPool<T>& GetInstance(int threadNum = 10, int cap = 20) {
        static ThreadPool<T> instance(threadNum, cap);
        return instance;
    }

    //传入任务指针
    void push(T td)
    {
        taskQueue_.push(td);
    }

   void Start()
   {
        for(int i=0;i<threadNum_;++i){
            pthread_t pid;
            pthread_create(&pid,nullptr,TreadRun,this);
            pthread_detach(pid);//分离线程
        }
   }
private:
   ThreadPool(int threadNum = 10,int cap = 20)
   :threadNum_(threadNum),taskQueue_(cap)
   {

   } 

   //线程处理函数
   static void* TreadRun(void *arg)
   {
        ThreadPool *pool = static_cast<ThreadPool*>(arg);
        while(true){
            T td = pool->taskQueue_.pop();
            td->run();
            delete td;
        }
        return nullptr;
   }

private:
    BlockQueue<T> taskQueue_;
    int threadNum_;
};